/**
 * 操作t_content表
 */

// 引入数据源
let pool = require('../util/datasource');

exports.queryList = function (data) {

    return new Promise((resolve, reject) => {
        let sql = `SELECT
        t_content_pk,
        title,
        t_cat_plant_fk,
        subtitle,
        image_path,
        publish_time 
    FROM
        t_content c 
    WHERE STATUS = 1`;

        const params = [];
        sql += buildCondition(data, params);


        // 打开了分页
        if (data.paging) {
            sql += ` order by ${data.order} LIMIT ?,? `;
            params.push(data.begin);
            params.push(data.rows);
        }

        console.log("sql = ", sql);
        console.log("params = ", params);

        // 执行SQL步骤：1、获取连接
        pool.getConnection((err, connection) => {
            if (err) {
                console.log('[SELECT ERROR] - ', err.message);
                reject(null);
                return;
            }

            // 2、使用连接执行SQL
            // result：查询结果集（可以理解成一个数组）
            connection.query(sql, params, function (err, result) {
                if (err) {
                    console.log("查询出错：", err);
                    reject(null);
                    return;
                }

                // 3、释放连接
                connection.release();

                resolve(result);

            });
        })
    })
}

// 查询总行数
exports.queryCount = function (data) {
    return new Promise((resolve, reject) => {
        let sql = `SELECT
        COUNT(1) 
    FROM
        t_content c 
    WHERE STATUS = 1`;

        let params = [];
        sql += buildCondition(data, params);

        console.log("sql = ", sql);
        console.log("params = ", params);

        // 执行SQL步骤：1、获取连接
        pool.getConnection((err, connection) => {
            if (err) {
                console.log('[SELECT ERROR] - ', err.message);
                reject(0);
                return;
            }

            // 2、使用连接执行SQL
            // result：查询结果集（可以理解成一个数组）
            connection.query(sql, params, function (err, result) {
                if (err) {
                    console.log("查询出错：", err);
                    reject(0);
                    return;
                }

                // 3、释放连接
                connection.release();
                resolve(result[0].c);

            });
        })
    });
}

// 查询行数和查询列表的where条件需要一致，所以提出方法
function buildCondition(data, params) {
    let sql = "";
    if (data.t_cat_plant_fk) {
        // ?表示占位符，进行预编译SQL语句
        sql += ` AND c.t_cat_plant_fk = ? `;
        params.push(data.t_cat_plant_fk);
    }
    if (data.title) {
        sql += ` AND c.title LIKE CONCAT('%',?,'%')`;
        params.push(data.title);
    }
    return sql;
}